import { WebchatModule } from '@/store/modules/webchat'
import { CommonModule } from '@/store/modules/common'
import { BreakStyleObj, PlatIcon } from '@/views/webchat/webchatInterface'
let doMain = ''
let emojiConfig: any = {}
export function msgConvertion (data: any, isShowHyperlinks?: boolean) {
  // isShowHyperlinks(是否转换成超链接)
  if (typeof data !== 'string') {
    return data
  }
  const dataNew = data
  const array0 = dataNew.match(/src=|href=/) || []
  let obstr = dataNew
  if (!isShowHyperlinks) {
    if (!(array0[0])) {
      const re = /((https|http|ftp|rtsp|mms)?:\/\/)?(([0-9a-z_!~*'().&=+$%-]+: )?[0-9a-z_!~*'().&=+$%-]+@)?(([0-9]{1,3}\.){3}[0-9]{1,3}|([0-9a-z_!~*'()-]+\.)*([0-9a-z][0-9a-z-]{0,61})?[0-9a-z]\.[a-z]{2,6})(:[0-9]{1,4})?(((\/[0-9a-z_!~*'().;?:@&=+$,%#-]+)+\/?)|(\/?))/gi
      const re1 = /^(http:\/\/|https:\/\/)?/
      let arry1
      const arry2: any = []
      while ((arry1 = re.exec(dataNew)) !== null) {
        arry2.push(arry1[0])
        obstr = obstr.replace(arry1[0], '######')
      }
      let subos = ''
      if (arry2.length) {
        for (let i = 0; i < arry2.length; i++) {
          const arry3 = re1.exec(arry2[i])
          if (arry3 && arry3[0]) {
            subos = '<a href="' + arry2[i] + '" target="_blank" class="webchatLink">' + arry2[i] + '</a>'
          } else {
            subos = '<a href="http://' + arry2[i] + '" target="_blank" class="webchatLink">' + arry2[i] + '</a>'
          }
          obstr = obstr.replace('######', subos)
        }
      }
    }
  }
  if (Object.keys(emojiConfig).length === 0) {
    emojiConfig = WebchatModule.webchatEmoji
  }
  if (!doMain) {
    const initConfig: any = CommonModule.initConfig
    doMain = initConfig && initConfig.qiniuDomainMap ? initConfig.qiniuDomainMap.im + '/' : ''
  }

  // 匹配所有 以:开头、以:结尾；切不包括:: 的字符串
  const emojiCode = obstr.match(/:[^:]+:/g)
  if (emojiCode) { // 如果匹配到了表情
    emojiCode.map((v: any) => {
      // 表情代码的索引
      const curEmoji: any = emojiConfig.bookArray.find((emj: any) => emj.str === v)
      if (curEmoji && curEmoji.index > -1) {
        const xOffset = -(emojiConfig.emojiSize * (curEmoji.index % emojiConfig.columnNum))
        const yOffset = -(emojiConfig.emojiSize * (parseInt((curEmoji.index / emojiConfig.columnNum).toString(), 0)))
        // 回显的html代码
        const htmlCode = `<span style="background: url(${doMain + emojiConfig.elvesFigureUrl}) no-repeat;` +
          `background-position:${xOffset}px ${yOffset}px;` +
          'background-size: 1000% auto;' +
          `width: ${emojiConfig.emojiSize}px;height: ${emojiConfig.emojiSize}px;display: inline-block;` +
          `margin: ${emojiConfig.echoMargin};` +
          '"></span>'
        obstr = obstr.replace(v, htmlCode)
      }
    })
  }
  return obstr
}
